package cn.birdbaby.plugins.selector.field;

import com.google.common.collect.Maps;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * @author llorando 6/8/24 5:14 pm
 */
public final class FieldSelectorRegistry {
    private static Map<String, ? extends PsiFieldSelector> annotator;

    private FieldSelectorRegistry() {
        //防止单例模式被破坏
        throw new UnsupportedOperationException();
    }

    static {
        //启动时加载，避免运行时才发现异常
        initProcessors();
    }
    public static Set<String> getSupportedAnnotations() {
        return annotator.keySet();
    }

    public static PsiFieldSelector find(String annotationClassName) {
        if( annotator.get(annotationClassName)==null){
            return annotator.get("default");
        }
        return annotator.get(annotationClassName);
    }

    public static void initProcessors() {
        Map<String, PsiFieldSelector> map = Maps.newLinkedHashMap();
        ServiceLoader<PsiFieldSelector> processors = ServiceLoader.load(PsiFieldSelector.class, PsiFieldSelector.class.getClassLoader());
        Iterator<PsiFieldSelector> iterator = processors.iterator();

        while(iterator.hasNext()) {
            PsiFieldSelector next = iterator.next();
            String annotationName = next.getName();
            map.put(annotationName, next);
        }

        annotator = map;
    }
}
